package com.itheima.dao;

import com.itheima.bean.Order;
import com.itheima.bean.Restaurant;
import com.itheima.exception.UserException;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    private static String ordersFilePath = "take-away-system/src/com/itheima/data/orders.oxt";

    @Override
    public List<Order> saveOrder(Order order) throws UserException, IOException {
        try {
            // 2. 获取所有orders
            final List<Order> orders = getOrders();

            // 3. 添加到列表
            // 判断是否已存在
            final int index = orders.indexOf(order);
            if (index > -1) {
                orders.set(index, order);
            } else {
                orders.add(order);
            }

            // 4. 保存列表到文件
            saveOrders(orders);

            return orders;
        } catch (Exception e) {
            e.printStackTrace();
            return getOrders();
        }
    }

    @Override
    public Order viewOrder(String orderId) throws UserException, IOException {
        final List<Order> orders = getOrders();
        for (Order order : orders) {
            if (orderId.equals(order.getOrderId())) {
                return order;
            }
        }
        return null;
    }

    // 查询所有的订单
    public List<Order> getOrders() throws IOException {
        try {
            // 1. 序列流读取
            final ObjectInputStream ois = new ObjectInputStream(new FileInputStream(ordersFilePath));

            // 2. 读取
            final List<Order> orders = (List<Order>) ois.readObject();

            // 3. 关闭流
            ois.close();

            return orders;
        } catch (FileNotFoundException e) {
            List<Order> orders = new ArrayList<>();
            saveOrders(orders);
            return orders;
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
            List<Order> orders = new ArrayList<>();
            return orders;
        }
    }

    // 保存订单列表
    public void saveOrders(List<Order> orders) throws IOException {
        // 1. 序列流读取
        final ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(ordersFilePath));

        // 2. 写入
        oos.writeObject(orders);

        // 3. 关闭流
        oos.close();
    }
}
